﻿Imports Aspose.Words
Imports System.Net
Imports System.IO
Imports System.IO.Path
Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_QuanLyHoSoThongBaoThuHoi_ThongBao
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Dim itm As New ListItem("--- Chọn ---", "  ")
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Not Request("Certifiedid") Is Nothing AndAlso Request("Certifiedid") <> 0 Then
                hidID.Value = Request("Certifiedid")
                Load2Grid()
            End If
        End If
    End Sub
    Protected Sub Load2Grid()
        Using _data As New VSEntities

            Dim _curHuyenId As Integer = Session("HuyenId")
            'load List PrositionDict
            Dim _j = (From q In _data.PositionDicts Order By q.Sort Select q).ToList
            With ddlCertifiedSignerPosition
                .DataSource = _j
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            With ddlCertifiedSignFor
                .DataSource = _j
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            'load list StaffDict
            Dim _SN = (From q In _data.StaffDicts Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList
            With ddlCertifiedSignerName
                .DataSource = _SN
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            Dim _BH = (From q In _data.StaffDicts Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList
            With ddlCertifiedBeHaft
                .DataSource = _BH
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With


            'load giấy đề nghị nếu có rồi
            'Dim intUserId As Integer = IIf(IsNothing(Session("UserID")), 0, Session("UserID"))
            'Dim use = (From q In _data.Users Where q.UserId = intUserId Select q.UserName).FirstOrDefault

            Dim p = (From q In _data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q).FirstOrDefault

            CapNhatMCC.Visible = False
            If Not p Is Nothing Then
                'show link Update MCC
                If Not p.SoBienNhan Is Nothing Then
                    Using abc As New AutoDevModel.AutoDevEntities
                        Dim kkkk = (From q In abc.HoSoes Where q.SoBienNhan = p.SoBienNhan And q.HuyenId = _curHuyenId Select q).FirstOrDefault
                        If Not kkkk Is Nothing Then
                            CapNhatMCC.Visible = True
                            hplLinkMcc.NavigateUrl = "../../Page/TiepNhan/UpdateMcc.aspx?s=" & kkkk.SoBienNhan.ToString
                            hplLinkMcc.Text = "đây"
                        End If
                    End Using
                End If

                If Not p.CertifiedCode Is Nothing AndAlso p.CertifiedCode <> "" Then
                    txtCertifiedCode.Text = p.CertifiedCode
                    If Not p.CertifiedDate Is Nothing Then
                        txtCertifiedDate.Text = CType(p.CertifiedDate, Date).ToString("dd/MM/yyyy")
                    Else

                        txtCertifiedDate.Text = Now.Date.ToString("dd/MM/yyyy")
                    End If
                Else
                End If
                'thong tin ca nhan


                'load CertifiedProvinderOrg by DeptCertifieds
                Dim _l = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList

                With ddlCertifiedProviderOrg
                    .DataSource = _l
                    .DataValueField = "Name"
                    .DataTextField = "Name"
                    .DataBind()
                    .Items.Insert(0, itm)
                End With
                'load CertifiedDeptName by DeptCertifieds
                With ddlCertifiedDeptName
                    .DataSource = _l
                    .DataValueField = "Name"
                    .DataTextField = "Name"
                    .DataBind()
                    .Items.Insert(0, itm)
                End With
                Dim _DoViCap = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId And q.Code = "001" Order By q.Sort Select q.Name).FirstOrDefault
                Dim _PhongBanCap = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId And q.Code = "002" Order By q.Sort Select q.Name).FirstOrDefault
                
                'thông tin hộ
                txtBiz_VietNam.Text = IIf(IsNothing(p.Biz_VietName) = True, "", p.Biz_VietName) 'tên hộ kinh doanh
                txtOw_Name.Text = IIf(IsNothing(p.Ow_Name) = True, "", p.Ow_Name) 'tên hộ đại diện hộ
                txtBiz_HeadOffice.Text = IIf(IsNothing(p.Biz_HeadOffice) = True, "", p.Biz_HeadOffice) 'địa chỉ kinh doanh
                txtOw_Resident.Text = IIf(IsNothing(p.Ow_Resident) = True, "", p.Ow_Resident) 'địa chỉ kinh doanh
                'lấy thông tin thông báo vi phạm
                Dim _TBViPham = (From q In _data.CertifiedHouseThongBaos Where q.CertifiedID = hidID.Value And q.HuyenId = _curHuyenId Select q).FirstOrDefault
                If Not _TBViPham Is Nothing Then
                    If Not _TBViPham.SoThongBao Is Nothing AndAlso _TBViPham.SoThongBao <> "" Then
                        txtSoThongBao.Text = _TBViPham.SoThongBao
                        If Not _TBViPham.NgayThongBao Is Nothing Then
                            txtNgayThongBao.Text = CType(_TBViPham.NgayThongBao, Date).ToString("dd/MM/yyyy")
                        Else

                            txtNgayThongBao.Text = Now.Date.ToString("dd/MM/yyyy")
                        End If
                    Else
                        txtSoThongBao.Text = btnSoThongBao()
                    End If
                    txtSoBienBan.Text = IIf(IsNothing(_TBViPham.SoBienBan) = True, "", _TBViPham.SoBienBan) 'số biên bản
                    If Not _TBViPham.NgayLapBienBan Is Nothing Then
                        txtNgayLapBienBan.Text = CType(_TBViPham.NgayLapBienBan, Date).ToString("dd/MM/yyyy")
                    End If
                    txtNoiDungBienBan.Text = IIf(IsNothing(_TBViPham.NoiDungBienBan) = True, "", _TBViPham.NoiDungBienBan) ' nội dung biên bản
                    txtNoiDungViPham.Text = IIf(IsNothing(_TBViPham.NoiDungViPham) = True, "", _TBViPham.NoiDungViPham) 'nội dung vi phạm
                    'Đơn vị cấp
                    If Not _TBViPham.TenCoQuan Is Nothing And _TBViPham.TenCoQuan <> "" Then
                        ddlCertifiedProviderOrg.SelectedValue = _TBViPham.TenCoQuan
                    Else
                        ddlCertifiedProviderOrg.SelectedValue = _DoViCap
                    End If
                    'Phòng ban cấp
                    If Not _TBViPham.TenPhongBan Is Nothing And _TBViPham.TenPhongBan <> "" Then
                        ddlCertifiedDeptName.SelectedValue = _TBViPham.TenPhongBan
                    Else
                        ddlCertifiedDeptName.SelectedValue = _PhongBanCap
                    End If
                    'Người ký
                    If Not _TBViPham.TenNguoiKy Is Nothing Then
                        ddlCertifiedSignerName.SelectedValue = _TBViPham.TenNguoiKy
                    Else
                        ddlCertifiedSignerName.SelectedValue = ""
                    End If
                    'Chức vụ người ký
                    If Not _TBViPham.ChucVuNguoiKy Is Nothing Then
                        ddlCertifiedSignerPosition.SelectedValue = _TBViPham.ChucVuNguoiKy
                    Else
                        ddlCertifiedSignerPosition.SelectedValue = ""
                    End If
                Else
                    txtSoThongBao.Text = btnSoThongBao()
                    ddlCertifiedProviderOrg.SelectedValue = _DoViCap
                    ddlCertifiedDeptName.SelectedValue = _PhongBanCap
                    ddlCertifiedSignerName.SelectedValue = ""
                    ddlCertifiedSignerPosition.SelectedValue = ""
                End If
                
            End If

        End Using
    End Sub
    Protected Function btnSoThongBao() As String
        Dim strCode As String = ""
        Dim _curHuyenId As Integer = Session("HuyenId")
        Using _data As New VSEntities
            Dim curCode As String = (From q In _data.Provinces Where q.Id = _curHuyenId Select q.Code).FirstOrDefault
            Dim max As String = (From q In _data.CertifiedHouseThongBaos Where q.HuyenId = _curHuyenId And q.SoThongBao.Contains(curCode) And q.NgayThongBao > "2014/01/01" Order By q.SoThongBao Descending Select q.SoThongBao).FirstOrDefault
            '52I2416
            Dim HuyenCode = (From q In _data.Provinces Where q.Id = _curHuyenId Select q.Code).FirstOrDefault & "TB"
            Try
                Dim _new As Integer = CType(max.Replace(HuyenCode, ""), Integer) + 1
                If _new > 0 Then
                    strCode = HuyenCode & _new.ToString.PadLeft(5)
                Else
                    strCode = HuyenCode & "8000" & _new.ToString.PadLeft(5)
                End If
            Catch ex As Exception
                strCode = HuyenCode & "8000" & "1"
            End Try
            hidSoThongBao.Value = strCode ' lưu vao hidden field để lưu
            txtNgayThongBao.Text = Now.Date.ToString("dd/MM/yyyy")
            Return strCode

        End Using
    End Function
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub

    Protected Sub btnExportWord_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportWord.Click
        UpdateThongtin()
        Dim strDocFile = getDocFile()
        Dim strFileName As String = strDocFile.Split("\")(strDocFile.Split("\").Length - 1)
        Excute_Javascript("SetDownFile('" & MainDomain & "TBGCN/" & strFileName & "');", Me.Page)
    End Sub
    Protected Sub btnExportPdf_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportPdf.Click
        UpdateThongtin()
        Dim strDocFile = getDocFile()
        'save PDF
        Dim strPdfFile As String = strDocFile.Replace(".doc", ".pdf")
        If Not File.Exists(strPdfFile) Then
            Dim licenseFile As String = Server.MapPath("~") & "\bin\Aspose.Words.lic"
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)
                doc.Save(strPdfFile, SaveFormat.Pdf)
                If Not IsNothing(doc) Then
                    doc = Nothing
                End If
            End If
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            Dim strFileName As String = strPdfFile.Split("\")(strPdfFile.Split("\").Length - 1)

            Response.Redirect(MainDomain & "TBGCN/" & strFileName)
        End If



    End Sub

    Function getDocFile() As String
        Dim curHuyenId As Integer = Session("HuyenId")
        Dim strResult As String = ""
        Try
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            If Not applicationPath.EndsWith("\") Then
                applicationPath = applicationPath + "\"
            End If
            Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Words.lic")
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)

                Dim strDocFile As String = applicationPath & "Template\ThongBaoThuHoi.doc"
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)

                Dim cls As New clsDAPrint
                Dim dt As DataTable = cls.CertifiedHouseholdThongBaoSelectById(hidID.Value, curHuyenId)
                cls.Destructor()
                cls = Nothing
                If dt.Rows.Count > 0 Then
                    doc.MailMerge.Execute(dt)
                    Dim builder As DocumentBuilder = New DocumentBuilder(doc)
                    Using _data As New VSEntities
                        Dim _tb = (From q In _data.CertifiedHouseThongBaos Where q.CertifiedID = hidID.Value And q.HuyenId = curHuyenId Select q).FirstOrDefault
                        If Not _tb Is Nothing Then
                            'ngày ra thông báo
                            Dim _date As Date = CType(_tb.NgayThongBao, Date)
                            Dim _H = (From j In _data.Provinces Where j.Id = curHuyenId Select j).FirstOrDefault
                            builder.MoveToMergeField("NgayRaThongBao")
                            If Not _tb.NgayThongBao Is Nothing Then
                                builder.Write(_H.Title & ",ngày " & _date.Day & " tháng " & _date.Month & " năm " & _date.Year)
                            Else
                                builder.Write("")
                            End If
                            'đơn vị đăng ký kinh doanh
                            builder.MoveToMergeField("TENCOQUANDANGKY")
                            If Not _tb.NgayThongBao Is Nothing Then
                                builder.Write(_tb.DonViQuanLy)
                            Else
                                builder.Write("")
                            End If
                            'lấy tên hộ kinh doanh
                            Dim _Biz = (From h In _data.CertifiedHouseholds Where h.CertifiedID = _tb.CertifiedID Select h).FirstOrDefault

                            If Not _Biz Is Nothing Then
                                builder.MoveToMergeField("TENHOKINHDOANH")
                                Dim _strBiz_VietName As String = IIf(IsNothing(_Biz.Biz_VietName) = True, "", _Biz.Biz_VietName)
                                If Not _strBiz_VietName Is Nothing And _strBiz_VietName <> "" Then
                                    builder.Write(_strBiz_VietName) 'tên hộ kinh doan
                                Else
                                    builder.Write("")
                                End If

                                builder.MoveToMergeField("TENHOKINHDOANH_HOVIPHAM")
                                If Not _Biz Is Nothing Then
                                    builder.Write(IIf(IsNothing(_Biz.Biz_VietName) = True, "", _Biz.Biz_VietName)) 'tên hộ kinh doanh
                                Else
                                    builder.Write("")
                                End If
                            End If

                        End If

                    End Using
                    strResult = applicationPath & "TBGCN"
                    If Not Directory.Exists(strResult) Then
                        Directory.CreateDirectory(strResult)
                    End If
                    If Not strResult.EndsWith("\") Then
                        strResult = strResult + "\"
                    End If
                    'set filename = soCN

                    strResult &= txtSoThongBao.Text & "-" & Format(Now, "yyyyMMddfff") & ".doc"
                    doc.Save(strResult, Aspose.Words.SaveFormat.Doc)
                    If Not IsNothing(doc) Then
                        doc = Nothing
                    End If

                End If
            End If
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/QuanLyHoSoThongBaoThuHoi/List.aspx';", Me.Page, True)
        End Try

        Return strResult
    End Function

    Protected Sub UpdateThongtin()
        Using _data As New VSEntities
            Dim _curHuyenId As Integer = Session("HuyenId")
            Dim p = (From k In _data.CertifiedHouseholds Where k.CertifiedID = hidID.Value And k.ProvinceId = _curHuyenId Select k).FirstOrDefault
            If Not p Is Nothing Then
                Dim _Checktb = (From q In _data.CertifiedHouseThongBaos Where q.CertifiedID = hidID.Value And q.HuyenId = _curHuyenId Select q).FirstOrDefault
                If _Checktb Is Nothing Then
                    Dim _tb As New VSModel.CertifiedHouseThongBao
                    Try
                        _tb.SoThongBao = txtSoThongBao.Text.Trim()
                        _tb.NgayThongBao = StringToDate(txtNgayThongBao.Text.Trim())
                        _tb.TenCoQuan = ddlCertifiedProviderOrg.SelectedValue 'đơn vị cấp
                        Dim _Profile = (From q In _data.CertifiedHouseProfileCoQuans Where q.HuyenId = _curHuyenId Select q).FirstOrDefault
                        If Not _Profile Is Nothing Then
                            _tb.DiaChiCoQuan = IIf(IsNothing(_Profile.DiaChiCoQuan) = True, "", _Profile.DiaChiCoQuan) 'địa chỉ cơ quan
                            _tb.DienThoai = IIf(IsNothing(_Profile.DienThoai) = True, "", _Profile.DienThoai) 'Điện thoai
                            _tb.Fax = IIf(IsNothing(_Profile.Fax) = True, "", _Profile.Fax) ' fax
                            _tb.Email = IIf(IsNothing(_Profile.Email) = True, "", _Profile.Email) ' Email
                            _tb.Website = IIf(IsNothing(_Profile.Website) = True, "", _Profile.Website) 'Website
                        End If
                        _tb.SoBienBan = txtSoBienBan.Text.Trim()
                        _tb.DonViQuanLy = ddlCertifiedDeptName.SelectedValue 'đơn vị cấp
                        _tb.TenPhongBan = ddlCertifiedDeptName.SelectedValue ' phòng ban cấp
                        _tb.NgayLapBienBan = StringToDate(txtNgayLapBienBan.Text.Trim())
                        _tb.NoiDungBienBan = txtNoiDungBienBan.Text.Trim()
                        _tb.NoiDungViPham = txtNoiDungViPham.Text.Trim()
                        _tb.SoGCN = txtCertifiedCode.Text.Trim() 'số GCN
                        _tb.CMND = txtCertifiedDate.Text.Trim() 'ngày cấp GCN
                        _tb.ChucVuNguoiKy = ddlCertifiedSignerPosition.SelectedValue 'chức vụ người ký
                        _tb.TenNguoiKy = ddlCertifiedSignerName.SelectedValue ' tên người ký
                        _tb.NgayTao = Now
                        _tb.NguoiTao = Session("UserName")
                        _tb.HuyenId = Session("HuyenId")
                        _tb.StatusId = TinhTrangHoSo.Daduyet
                        _tb.CertifiedID = hidID.Value
                        _data.CertifiedHouseThongBaos.AddObject(_tb)
                        Dim strLog As String = "Thông báo:" & txtCertifiedCode.Text.Trim() & ", tên hộ: " & txtBiz_VietNam.Text.Trim()
                        Insert_App_Log("Insert  Thông báo:" & strLog & "", Function_Name.CertifiedChamDut, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Catch ex As Exception
                        log4net.Config.XmlConfigurator.Configure()
                        log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                    End Try
                Else
                    Try
                        _Checktb.SoThongBao = txtSoThongBao.Text.Trim()
                        _Checktb.NgayThongBao = StringToDate(txtNgayThongBao.Text.Trim())
                        _Checktb.TenCoQuan = ddlCertifiedProviderOrg.SelectedValue 'đơn vị cấp
                        Dim _Profile = (From q In _data.CertifiedHouseProfileCoQuans Where q.HuyenId = _curHuyenId Select q).FirstOrDefault
                        If Not _Profile Is Nothing Then
                            _Checktb.DiaChiCoQuan = IIf(IsNothing(_Profile.DiaChiCoQuan) = True, "", _Profile.DiaChiCoQuan) 'địa chỉ cơ quan
                            _Checktb.DienThoai = IIf(IsNothing(_Profile.DienThoai) = True, "", _Profile.DienThoai) 'Điện thoai
                            _Checktb.Fax = IIf(IsNothing(_Profile.Fax) = True, "", _Profile.Fax) ' fax
                            _Checktb.Email = IIf(IsNothing(_Profile.Email) = True, "", _Profile.Email) ' Email
                            _Checktb.Website = IIf(IsNothing(_Profile.Website) = True, "", _Profile.Website) 'Website
                        End If
                        _Checktb.SoBienBan = txtSoBienBan.Text.Trim()
                        _Checktb.DonViQuanLy = ddlCertifiedDeptName.SelectedValue 'đơn vị cấp
                        _Checktb.TenPhongBan = ddlCertifiedDeptName.SelectedValue ' phòng ban cấp
                        _Checktb.NgayLapBienBan = StringToDate(txtNgayLapBienBan.Text.Trim())
                        _Checktb.NoiDungBienBan = txtNoiDungBienBan.Text.Trim()
                        _Checktb.NoiDungViPham = txtNoiDungViPham.Text.Trim()
                        _Checktb.SoGCN = txtCertifiedCode.Text.Trim() 'số GCN
                        _Checktb.CMND = txtCertifiedDate.Text.Trim() 'ngày cấp GCN
                        _Checktb.ChucVuNguoiKy = ddlCertifiedSignerPosition.SelectedValue 'chức vụ người ký
                        _Checktb.TenNguoiKy = ddlCertifiedSignerName.SelectedValue ' tên người ký
                        _Checktb.NgaySua = Now
                        _Checktb.NguoiSua = Session("UserName")
                        _Checktb.HuyenId = Session("HuyenId")
                        Dim strLog As String = "Thông báo:" & txtCertifiedCode.Text.Trim() & ", tên hộ: " & txtBiz_VietNam.Text.Trim()
                        Insert_App_Log("Edit  Thông báo:" & strLog & "", Function_Name.CertifiedChamDut, Audit_Type.Edit, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Catch ex As Exception
                        log4net.Config.XmlConfigurator.Configure()
                        log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                    End Try
                End If
                _data.SaveChanges()
            End If
        End Using
    End Sub
End Class

